package com.doit.day03;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.roaringbitmap.RoaringBitmap;

import java.time.Duration;
import java.util.*;

public class BitMapCountUV {

    public static void main(String[] args) {
        //创建一个bitMap对象
        RoaringBitmap bitmap = RoaringBitmap.bitmapOf();

        new Thread(new BitMapConsumerTask(bitmap)).start();
        //任务调度
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int cardinality = bitmap.getCardinality();
                //这个结果
                System.out.println("当前时间："+System.currentTimeMillis()+",的uv是："+cardinality);
            }
        },10000,5000);
    }
}

class BitMapConsumerTask implements Runnable{
    private RoaringBitmap bitmap;


    public BitMapConsumerTask(RoaringBitmap bitmap){
        this.bitmap = bitmap;
    }

    @Override
    public void run() {
        Properties props = new Properties();
        props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"linux01:9092,linux02:9092,linux03:9092");
        props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.setProperty(ConsumerConfig.GROUP_ID_CONFIG,"abcd");
        props.setProperty("allow.auto.create.topics","true");
        props.setProperty("auto.offset.reset","earliest");
        props.setProperty("enable.auto.commit","true");
        props.setProperty("auto.commit.interval.ms","3000");

        //创建kafka的消费者对象
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
        consumer.subscribe(Arrays.asList("event-log"));

        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(Integer.MAX_VALUE));
            for (ConsumerRecord<String, String> record : poll) {
                //写进去的json串
                String json = record.value();
                EventLog eventLog = JSON.parseObject(json, EventLog.class);
                long guid = eventLog.getGuid();
                //把每个guid放到set集合中去
                bitmap.add((int)guid);
            }
        }
    }
}
